package com.jintian.smart.kernel.common.orm;

import cn.hutool.core.util.ClassUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jintian.smart.kernel.core.exception.ResultWrapperException;
import com.jintian.smart.kernel.core.web.RestResultBuilder;
import com.jintian.smart.kernel.core.web.RestResultWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.WeakHashMap;

@Slf4j
@ControllerAdvice
public class RestResultResponseBodyAdvice implements ResponseBodyAdvice<Object>, ApplicationContextAware {

    private final Map<Method, RestResultWrapper> supportsCache = new WeakHashMap<>();

    private ApplicationContext applicationContext;

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (supportsCache.containsKey(returnType.getMethod())) {
            return supportsCache.get(returnType.getMethod()) != null;
        }
        RestResultWrapper wrapper;
        synchronized (supportsCache) {
            if (supportsCache.containsKey(returnType.getMethod())) {
                wrapper = supportsCache.get(returnType.getMethod());
            }
            wrapper = getResultWrapper(returnType);
            supportsCache.put(returnType.getMethod(), wrapper);
        }
        return wrapper != null;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        RestResultWrapper wrapper = supportsCache.get(returnType.getMethod());
        if (body != null) {
            for (Class<?> c : wrapper.excludeClasses()) {
                if (c.isAssignableFrom(body.getClass())) {
                    return body;
                }
            }
            for (String name : wrapper.excludeClassNames()) {
                try {
                    Class<?> c = ClassUtil.getClass(name);
                    if (c.isAssignableFrom(body.getClass())) {
                        return body;
                    }
                } catch (Exception e) {
                    log.error("无法加载{}", name);
                }
            }
        }
        String beanName = wrapper.wrapperRef();
        try {
            RestResultBuilder builder = this.applicationContext.getBean(beanName, RestResultBuilder.class);
            Object ret;
            if (builder.except(body)) {
                return body;
            } else {
                ret = builder.data(body);
                // if (body instanceof String ||
                // returnType.getGenericParameterType().equals(String.class)) {
                // // return new ObjectMapper().writeValueAsString(ret);
                // }
                return ret;
            }
        } catch (Exception e) {
            throw new ResultWrapperException(e);
        }
    }

    private RestResultWrapper getResultWrapper(MethodParameter returnType) {
        RestResultWrapper wrapper = returnType.getMethod().getAnnotation(RestResultWrapper.class);
        if (wrapper == null) {
            Class<?> declaringClass = returnType.getMethod().getDeclaringClass();
            wrapper = declaringClass.getAnnotation(RestResultWrapper.class);
        }
        return wrapper;
    }
}
